package com.luo.sc.oidc.authserver.controller.kaptcha;

import com.luo.sc.oidc.authserver.config.Oauth2ServerProps;
import com.luo.sc.oidc.authserver.enums.KaptchaTypeEnum;
import com.luo.sc.oidc.authserver.handler.kapatcha.DelegatingKapatchaProducer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;

/**
 * 图片验证码 - controller
 *
 * @author luohq
 * @version 1.0.0
 * @date 2022-02-14 14:52
 */
@Controller
@Slf4j
public class CaptchaController {

    @Resource
    private Oauth2ServerProps oauth2ServerProps;
    @Resource
    private DelegatingKapatchaProducer delegatingKapatchaProducer;
    /**
     * Map(验证码类型, 对应的验证码生成逻辑)
     */
    private Map<Integer, BiConsumer<HttpServletRequest, HttpServletResponse>> type2KaptchaFuncMap = new HashMap<>(3);

    @PostConstruct
    private void init() {
        this.type2KaptchaFuncMap.put(0, this.delegatingKapatchaProducer::responseWriteRandowmTypeKapatch);
        this.type2KaptchaFuncMap.put(KaptchaTypeEnum.TEXT.getCode(), this.delegatingKapatchaProducer::responseWriteTextKapatch);
        this.type2KaptchaFuncMap.put(KaptchaTypeEnum.MATH.getCode(), this.delegatingKapatchaProducer::responseWriteMathKapatch);
    }

    /**
     * 生成验证码图片
     *
     * @param request  请求对象
     * @param response 响应对象
     */
    @GetMapping(value = "${spring.security.oauth2.authserver.captcha-url:/captcha}")
    public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) {
        this.type2KaptchaFuncMap.get(this.oauth2ServerProps.getCaptchaType()).accept(request, response);
    }
}


